<template>
  <div class="authorizationDiv" v-if="isAuthorization">
    <div class="authorizationBg" @click="closeBox"></div>
    <div class="authorizationBtn">
      <div class="authorizationImg"><img src="/static/images/user/logo.png"> </div>
      <h1  class="authorizatioTitle">欢迎进入脑卫士~</h1>
      <!-- <button open-type="getUserInfo" @getuserinfo="bindGetUserInfo">进入脑卫士</button> -->
      <button open-type="getUserInfo" @getuserinfo="bindGetUserInfo">立即登录</button>
    </div> 
  </div>
</template>

<script>
  export default {
    data () {
      return {
        onOff: true,  //重复打开的
        isAuthorization: false, //是否显示按钮弹框，false默认不显示
        userDate: {}, //用户授权通过以后，获取到的用户昵称等信息
      }
    }, 
    mounted() {
      this.getUserInfo()
    },
    methods: {
      // closeBox(){
      //   this.isAuthorization = false
      // },
      getUserInfo(){
        if(wx.canIUse('button.open-type.getUserInfo')){//判断微信的版本
          if(this.onOff){
            wx.login({//调用登录接口，获取code
              success: (res) => {
                let url = "user/firstInit"
                let params = {
                  code: res.code
                }
                this.$http.post(url,params).then((data)=>{  //第一次发送code给后台，看看是否获取到用户信息
                  let reponseCode = data.data.code;
                  switch(reponseCode){
                      case 0://可以直接获取到昵称等等
                        this.isAuthorization = false 
                        let cookie = this.getCookie(data.header["Set-Cookie"]) 
                        // this.$store.dispatch("set_cookie",cookie)
                        wx.setStorageSync('set_cookie',cookie)
                        this.$store.dispatch("userInfo_init",data.data.data)
                        this.getcar()//进入页面就调取购物车 初始化
                        this.$emit("complete",true)
                        break;
                      case 2://授权弹框出现  没有获取openId，需要授权以后传加密信息
                        this.ifAccredit()
                        break;
                      case 3://相当于code失效，需要从新登录
                        this.getUserInfo() 
                        this.onOff = false;
                        break;
                    }     
                })
              },
              fail: (res)=>{
                console.log("失败")
              },
            }) 
          }
        }else{
          this.wxAlert("请升级到最新的微信版本")
        }
      },
      sendSecretData(userInfo){ //发送加密数据
        wx.login({
          success: (res) => {
            let url = "user/againInit"
            let params = {
              code: res.code,
              iv: userInfo.iv,
              encryptedData: userInfo.encryptedData,
            }
            this.$http.post(url,params).then((data)=>{ 
              if(data.data.code === 0){
                let cookie = this.getCookie(data.header["Set-Cookie"])
                // this.$store.dispatch("set_cookie",cookie)
                wx.setStorageSync('set_cookie',cookie)
                this.$store.dispatch("userInfo_init",data.data.data)
                this.getcar()//进入页面就调取购物车 初始化
                this.$emit("complete",true)
              }else if(data.data.code === 3){
                wx.hideLoading()
                this.isAuthorization = true
                this.sendSecretData(this.userDate)//发送加密数据
              }
            })
          },
          fail: (res)=>{
            console.log("失败")
          },
        })  
      },
      ifAccredit(){//判断用户是否需要授权
        wx.getSetting({
          success: (res) =>{ 
            if (res.authSetting['scope.userInfo']) { //用户已授权,
              console.log('已授权')
              wx.getUserInfo({
                withCredentials: true,
                lang: "zh_CN",
                success: (res)=>{
                  this.sendSecretData(res)//发送加密数据
                }
              })
            }else{ //用户还未授权过
              console.log('未授权')
              wx.hideLoading()
              this.isAuthorization = true
            }
          }
        })
      },

      bindGetUserInfo(e) {  //弹框的授权拒绝和允许
        console.log('用户昵称信息',e.mp.detail)
        this.userDate = e.mp.detail //用户授权通过以后，获取到的用户昵称等信息
        if (this.userDate.rawData){
           console.log('用户按了允许按钮')
          this.isAuthorization = false
          this.sendSecretData(this.userDate)//发送加密数据
        } else {
          this.isAuthorization = true
          console.log('用户按了拒绝按钮')
        }
      },
      getcar(){ //进入页面就调取购物车 初始化
        this.$http.get('cart','','',false).then((res)=>{ 
          console.log('购物车页面的res组件',res)
          this.$store.dispatch("createLineItem",res.data.data)
        })
      },
      getCookie (cookie){
        return cookie.split(";")[0]
      },
      wxAlert(txt){
        wx.showToast({
            title: txt,
            icon: "none",
            duration: 2000,
            mask: true
        })
      }
    }
  }
</script>

<style scoped>
.authorizationDiv{
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  z-index: 103;
  font-size: 50rpx;
  color: red;
}
.authorizationDiv .authorizationBg{
  width: 100%;
  height: 100%;
  background: black;
  opacity: 0.8; 
}
.authorizationDiv .authorizationBtn{
  padding: 0 30rpx;
  position: absolute;
  background: #fff;
  opacity: 1;
  width: 450rpx;
  height: 300rpx;
  border-radius: 10rpx;
  top: 50%;
  left: 50%;
  margin-left: -255rpx;
  margin-top: -150rpx;
}
.authorizationDiv .authorizationBtn .authorizationImg{
  width: 136rpx;
  height: 136rpx;
  margin: -68rpx auto 0;
}
.authorizationDiv .authorizationBtn .authorizationImg img{
  width: 100%;
  height: 100%;  
  display: block;
}
.authorizationDiv .authorizationBtn .authorizatioTitle{
  font-size: 30rpx;
  margin: 25rpx 0 45rpx;
  color: #000;
  text-align: center;
}
.authorizationDiv .authorizationBtn button{
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: #e1c7d2;
  font-size: 32rpx;
  color: #fff;
}
.authorizationDiv .authorizationBtn button::after{
  border: none;
}
</style>
